# coding=utf-8
import logging
import socket
import traceback

"""
log 怎么去写还有待讨论
"""
def get_ip(request):
	headers = request.headers
	return headers.get('X-Real-Ip') or headers.get('X-Forwarded-For')


def send_msg(msg, reminders=[]):
	return
	headers = {'Content-Type': 'application/json;charset=utf-8'}
	hostname = socket.gethostname()


# if has_app_context:
#     text = f'## get request ip: {get_ip(request)}\n{msg}',  # 消息正文
# else:
#     text = f'## Celery Error\n{msg}'

# data = {
# 	"msgtype": "markdown",  # 发送消息类型为文本
# 	"at": {
# 		"atMobiles": reminders,
# 		"isAtAll": False,  # 不@所有人
# 	},
# 	"markdown": {
# 		"title": hostname,
# 		"text": f'{msg}',  # 消息正文
# 	}
# }
# r = requests.post(DING_TALK_URL, data=json.dumps(data), headers=headers)
# return r.text


class MyLogger:
	def __init__(self, tag: str = 'LOGGING', clue: str = None):
		self._tag = tag
		self._clue = clue
		self.prefix = None
		self.log = logging.Logger("global")

		self.make_prefix()

	@property
	def tag(self):
		return self._tag

	@tag.setter
	def tag(self, value):
		self._tag = value
		self.make_prefix()

	@property
	def clue(self):
		return self._clue

	@clue.setter
	def clue(self, value):
		self._clue = value
		self.make_prefix()

	def make_prefix(self):
		prefix = '[{}]'.format(self._tag.upper())
		if self._clue:
			prefix = '{}[{}]'.format(prefix, self._clue)
		self.prefix = prefix

	def _make_log(self, msg):
		log_ = '{} {}'.format(self.prefix, msg)
		return log_

	def debug(self, msg):
		self.log.debug(self._make_log(msg))

	def info(self, msg):
		self.log.info(self._make_log(msg))

	def warning(self, msg):
		self.log.warning(self._make_log(msg))

	def error(self, msg):
		error_msg = self._make_log(msg)
		self.log.error(error_msg)
		self.info(send_msg(msg))

	def exception(self, e: Exception):
		msg = traceback.format_exc()
		self.error(msg)
